package com.tanhua.houtai.server.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;

import com.tanhua.domain.db.QuestionOption;
import com.tanhua.domain.db.SoulConclusion;
import com.tanhua.domain.db.SoulQuestion;
import com.tanhua.domain.db.SoulTest;
import com.tanhua.domain.vo.QuestionListVo;
import com.tanhua.dubbo.api.*;

import com.tanhua.houtai.server.service.XlsxService;


import org.apache.dubbo.config.annotation.Reference;
import org.apache.http.annotation.Contract;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.core.io.Resource;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class XlsxServiceImpl implements XlsxService {
    @Reference
    private SoulTestApi soulTestApi;
    @Reference
    private SoulQuestionApi questionApi;
    @Reference
    private QuestionOptionApi optionApi;
    @Reference
    private ConclusionApi conclusionApi;
    @Reference
    private QuestionListVoApi questionListVoApi;
    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer server;
    @Transactional
    public String saveXlsx(Workbook workbook) throws FileNotFoundException {
        try {
            //获取题目
            Sheet sheetAt = workbook.getSheetAt(0);
            int lastRowNum = sheetAt.getLastRowNum();
            //遍历第一个sheet存储题目信息
            for (int i = 1; i <=lastRowNum; i++) {
                Row row = sheetAt.getRow(i);
                String name = row.getCell(2).getStringCellValue();
                String coverPath = row.getCell(3).getStringCellValue();
                String level = row.getCell(4).getStringCellValue();
                Integer star=new Double(row.getCell(5).getNumericCellValue()).intValue();
                Integer titleId=new Double(row.getCell(1).getNumericCellValue()).intValue();
                //封装对象进行存储
                SoulTest soulTest=new SoulTest();
                soulTest.setName(name);
                //获取图片路径,上传到oss或者fdfs
                File file=new File(coverPath);
                FileInputStream inputStream = new FileInputStream(file);
                StorePath storePath = client.uploadFile(inputStream, file.length(), file.getName().split("\\.")[1], null);
                String path=server.getWebServerUrl()+"/"+storePath.getFullPath();
                soulTest.setCover(path);
                soulTest.setLevel(level);
                soulTest.setStar(star);
                soulTest.setIsLock(0);
                soulTestApi.insert(soulTest);
                //=======================================获取存储的id======================================================
                //获取存储题目获取id方便题目插入
                SoulTest soulTest1 = soulTestApi.selectOne(name);
                //遍历第二个sheet
                Sheet sheetAtQuestion = workbook.getSheetAt(1);
                int lastRowNumsheetQuestion = sheetAtQuestion.getLastRowNum();
                for (int i1 = 1; i1 <= lastRowNumsheetQuestion; i1++) {
                    Row row1 = sheetAtQuestion.getRow(i1);
                    int questionId=new Double(row1.getCell(1).getNumericCellValue()).intValue();
                    //判断questionId是否和之前的titleId是否一致，是一致就插入，不是一致不插入，并通过soulTest1.getId获取sid
                    if(questionId==titleId){
                        int sid=soulTest1.getId();
                        String question = row1.getCell(3).getStringCellValue();
                        SoulQuestion soulQuestion=new SoulQuestion();
                        soulQuestion.setSid(sid);
                        soulQuestion.setQuestion(question);
                        questionApi.insert(soulQuestion);
                        //将查询的已经存储的questionId，方便插入option
                        SoulQuestion soulQuestionOne = questionApi.selectOne(sid,question);
                        //获取该题目的编号,并且查询第三个sheet
                        int optionId=new Double(row1.getCell(2).getNumericCellValue()).intValue();
                        Sheet sheetAtOption = workbook.getSheetAt(2);
                        int lastRowNumOption = sheetAtOption.getLastRowNum();
                        for (int i2 = 1; i2 <=lastRowNumOption; i2++) {
                            Row row2 = sheetAtOption.getRow(i2);
                            int oid = new Double(row2.getCell(1).getNumericCellValue()).intValue();
                            //如果问题编号和之前的问题编号匹配代表同一个问题
                            if(oid==optionId){
                                String option = row2.getCell(2).getStringCellValue();
                                int score = new Double(row2.getCell(3).getNumericCellValue()).intValue();
                                int qid=soulQuestionOne.getId();
                                QuestionOption option1=new QuestionOption();
                                option1.setOptions(option);
                                option1.setScore(score);
                                option1.setQid(qid);
                                option1.setIsdefault(0);
                                optionApi.insert(option1);
                            }
                        }
                    }
                }
                //遍历第四个sheet,存储性格conclusion
                Sheet sheetAtConclusion = workbook.getSheetAt(3);
                int lastRowNumConclusion = sheetAtConclusion.getLastRowNum();
                for (int i1 = 1; i1 <=lastRowNumConclusion; i1++) {
                    Row rowConclusion = sheetAtConclusion.getRow(i1);
                    int tid =  new Double(rowConclusion.getCell(1).getNumericCellValue()).intValue();
                    if(tid==titleId){
                        String conclusion = rowConclusion.getCell(2).getStringCellValue();
                        String picPath = rowConclusion.getCell(3).getStringCellValue();
                        //上传fdfs
                        File fileClusion=new File(picPath);
                        FileInputStream inputStreamClu = new FileInputStream(fileClusion);
                        StorePath storePathClu= client.uploadFile(inputStreamClu, fileClusion.length(), fileClusion.getName().split("\\.")[1], null);
                        //fdfs路径
                        String pathClu=server.getWebServerUrl()+"/"+storePathClu.getFullPath();
                        String dimensions= rowConclusion.getCell(4).getStringCellValue();
                        int startScore = new Double(rowConclusion.getCell(5).getNumericCellValue()).intValue();
                        int endScore = new Double(rowConclusion.getCell(6).getNumericCellValue()).intValue();
                        SoulConclusion soulConclusion=new SoulConclusion();
                        //封装性格对象
                        soulConclusion.setStartscore(startScore);
                        soulConclusion.setEndscore(endScore);
                        soulConclusion.setCover(pathClu);
                        soulConclusion.setSid(soulTest1.getId());
                        soulConclusion.setDimensions(dimensions);
                        soulConclusion.setConclusion(conclusion);
                        conclusionApi.insert(soulConclusion);
                    }
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return "插入失败请检查excel";
        }
        return "插入成功";
    }

    public Page getsoul(int page, int pagesize,String name,String question) {
        Page page1=new Page(page,pagesize);
        Page<QuestionListVo> list = questionListVoApi.getList(page1,name,question);
        return list;
    }

    public void deleteOne(String id) {
        optionApi.deleteById(id);
    }

    public void updatehide(String id) {
        QuestionOption option1 = optionApi.selectOne(id);
        Integer isdefault = option1.getIsdefault();
        QuestionOption option=new QuestionOption();
        option.setId(Integer.parseInt(id));
        if(isdefault==1){
            option.setIsdefault(0);
            optionApi.updateById(option);
        }else {
            option.setIsdefault(1);
            optionApi.updateById(option);
        }
    }
    @Transactional
    public void updateoption(HashMap<String, Object> map) {
        String name = map.get("name").toString();
        int id = (int) map.get("id");
        String level =  map.get("level").toString();
        int star = Integer.parseInt(map.get("star").toString());
        String question = map.get("question").toString();
        String options = map.get("options").toString();
        int score = Integer.parseInt(map.get("score").toString());
        //根据id查询选项并跟新
        QuestionOption option = optionApi.selectById(id);
        option.setScore(score);
        option.setOptions(options);
        optionApi.updateById(option);

        //查询问题并且更新
        Integer qid = option.getQid();
        SoulQuestion soulQuestion = questionApi.selectById(qid);
        soulQuestion.setQuestion(question);
        questionApi.updateById(soulQuestion);

        Integer sid = soulQuestion.getSid();
        //查询主题并且更新
        SoulTest soulTest = soulTestApi.selectById(sid);
        soulTest.setName(name);
        soulTest.setLevel(level);
        soulTest.setStar(star);
        soulTestApi.updateById(soulTest);

    }

    public List<SoulTest> getallsoul() {
     List<SoulTest> list= soulTestApi.getSoulTest();
     return list;
    }

    public List<SoulQuestion> getallquestion(int id) {
        List<SoulQuestion> list= soulTestApi.getSoulQuestion(id);
        return list;
    }

    public void deleteChoice(String id, String qid) {
        if(qid==null){
            soulTestApi.deleteById(id);
        }else {
            soulTestApi.deleteByTwoId(qid);
        }
    }

    public Workbook getExcel() throws IOException {
        InputStream resourceAsStream = Resource.class.getResourceAsStream("/static/excel/question.xlsx");
        Workbook workbook=new XSSFWorkbook(resourceAsStream);
        return workbook;
    }
}
